package com.zsyh.jiujiu;

import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.zyh.toolslib.base.BaseActivity;
import com.example.zyh.toolslib.utils.EmptyUtil;
import com.example.zyh.toolslib.utils.SPUtils;
import com.google.gson.Gson;
import com.lwb.retrofit.RetrofitTask;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.proxy.impl.DefaultUpdateChecker;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yinglan.alphatabs.AlphaTabsIndicator;
import com.yinglan.alphatabs.OnTabChangedListner;
import com.zsyh.jiujiu.bean.MessageEvn;
import com.zsyh.jiujiu.bean.MyInfoBeeean;
import com.zsyh.jiujiu.bean.Updatagenxin;
import com.zsyh.jiujiu.dialog.TipDialog;
import com.zsyh.jiujiu.fragment.CarFragment;
import com.zsyh.jiujiu.fragment.MessageFragment;
import com.zsyh.jiujiu.fragment.MineFragment;
import com.zsyh.jiujiu.fragment.NewHomeFragment;
import com.zsyh.jiujiu.home.CardActtivity;
import com.zsyh.jiujiu.home.CxRenzhengActivity;
import com.zsyh.jiujiu.home.FaBuActivity;
import com.zsyh.jiujiu.home.LoginActivity;
import com.zsyh.jiujiu.home.SureOrderActivity;
import com.zsyh.jiujiu.net.MyObserver;
import com.zsyh.jiujiu.utils.CProgressDialogUtils;
import com.zsyh.jiujiu.utils.Constants;
import com.zsyh.jiujiu.utils.CustomUpdateParser;
import com.zsyh.jiujiu.utils.CustomUpdatePrompter;
import com.zsyh.jiujiu.utils.GlideCircleTransform;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.fl_content)
    FrameLayout flContent;
    @BindView(R.id.tab_view)
    AlphaTabsIndicator tabView;

    private static List<Fragment> fgList;
    private Fragment nowFragment;
    private int postion = 0;//记录栈位置
    private NewHomeFragment homeFragment;
    private CarFragment carFragment;
    private MessageFragment messageFragment;
    private MineFragment mineFragment;

    //声明mlocationClient对象
    private AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    private AMapLocationClientOption mLocationOption = null;





    @Override
    protected int initLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
        BarUtils.setStatusBarLightMode(this, false);

    }

    @Override
    protected void initData() {
        Updata();
        initFragment();
    }

    @Override
    protected void initEvent() {

    }

    private void initFragment() {
        fgList = new ArrayList<>();
        homeFragment = new NewHomeFragment();
        messageFragment=new MessageFragment();
        carFragment=new CarFragment();
        mineFragment=new MineFragment();
        fgList.add(homeFragment);
        fgList.add(messageFragment);
        fgList.add(null);
        fgList.add(carFragment);
        fgList.add(mineFragment);
        nowFragment = homeFragment;
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fl_content, homeFragment, "homeFragment");
        fragmentTransaction.hide(homeFragment);
        fragmentTransaction.show(homeFragment).commitAllowingStateLoss();
        initEven();
        if (PermissionUtils.isGranted(Permission.ACCESS_COARSE_LOCATION)) {
            startLoc();
        } else {
            showPermissionDailog();
        }

    }

    private void showPermissionDailog() {
        TipDialog tipDialog = new TipDialog(thisActivity);
        tipDialog.setContentTv("请在系统设置中开启定位服务，否则\n" +
                "可能影响您的使用。");
        tipDialog.setOnSureClickListener(new TipDialog.OnSureClickListener() {
            @Override
            public void confirm() {
                AndPermission.with(thisActivity).runtime().setting().start(Constants.PERMISSION_EXTERNAL_STORAGE);
            }
        });
        tipDialog.showPopupWindow();
    }

    private void initEven() {
        tabView.setOnTabChangedListner(new OnTabChangedListner() {
            @Override
            public void onTabSelected(int tabNum) {
                if(tabNum==2){
                    gettUser((String) SPUtils.get(thisActivity, "userid", ""));
                }else{
                    switchFragment(nowFragment, fgList.get(tabNum));
                    nowFragment = fgList.get(tabNum);
                }

            }
        });
    }



    /**
     * 切换Fragment
     * <p>(hide、show、add)
     *
     * @param fromFragment
     * @param toFragment
     */
    private void switchFragment(Fragment fromFragment, Fragment toFragment) {

        if (nowFragment != toFragment) {
            hideAllFragment();

            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            if (!toFragment.isAdded()) {    // 先判断是否被add过
                fragmentTransaction.add(R.id.fl_content, toFragment);
                fragmentTransaction.show(toFragment).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到activity中
            } else {
                fragmentTransaction.hide(fromFragment).show(toFragment).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void hideAllFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        for (int i = 0; i < fgList.size(); i++) {
            if (fgList.get(i) != null)
                fragmentTransaction.hide(fgList.get(i));

        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(MessageEvn messageInfo) {
        if (messageInfo.getMessage().equals("home")) {
            tabView.setTabCurrenItem(0);
            switchFragment(nowFragment, fgList.get(0));
            nowFragment = fgList.get(0);
        }else if (messageInfo.getMessage().equals("car")){
            tabView.setTabCurrenItem(3);
            switchFragment(nowFragment, fgList.get(3));
            nowFragment = fgList.get(3);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(EmptyUtil.isEmpty((String) SPUtils.get(thisActivity, "userid", ""))){
            ActivityUtils.startActivity(LoginActivity.class);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    private void startLoc() {
        mlocationClient = new AMapLocationClient(thisActivity);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位监听
        mlocationClient.setLocationListener(this);
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
        //启动定位
        mlocationClient.startLocation();
    }


    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                double latitude = amapLocation.getLatitude();
                double longitude = amapLocation.getLongitude();
                String city=amapLocation.getCity();
                String citycode=amapLocation.getAdCode();
                Log.e("dingwei",city+citycode+latitude+longitude+amapLocation.toStr()+"");
                SPUtils.put(thisActivity,"cityname",city);
                SPUtils.put(thisActivity,"citycode",citycode);
                SPUtils.put(thisActivity,"lat",latitude+"");
                SPUtils.put(thisActivity,"lon",longitude+"");

            } else {
                ToastUtils.showShort("定位失败，请重新进入");
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());

            }
        }
    }

    /**
     * getuser
     */
    public void gettUser(String userid) {
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .getUserById(userid)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this, false) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("Myinfo", JsonStr + "");
                        Gson gson = new Gson();
                        MyInfoBeeean myInfoBeeean = gson.fromJson(JsonStr, MyInfoBeeean.class);
                        if(!myInfoBeeean.getData().getIsCheck().equals("审核通过")){
                            Bundle bundlecard = new Bundle();
                            bundlecard.putString("name", myInfoBeeean.getData().getUserName());
                            bundlecard.putString("cardid",myInfoBeeean.getData().getUserIdcard());
                            bundlecard.putString("state",myInfoBeeean.getData().getIsCheck());
                            ActivityUtils.startActivity(bundlecard,CardActtivity.class);
                        }else{
                            Bundle bundlefa = new Bundle();
                            bundlefa.putString("goodid", "");
                            bundlefa.putString("userType", "");
                            bundlefa.putString("goodsTitle", "");
                            bundlefa.putString("goodsDesc", "");
                            bundlefa.putString("goodsPic", "");
                            bundlefa.putString("isNewGoods", "");
                            bundlefa.putString("goodsClass", "");
                            bundlefa.putString("goodsClassTwo", "");
                            bundlefa.putString("goodsClassThree", "");
                            bundlefa.putString("beginCount", "");
                            bundlefa.putString("stockCount", "");
                            bundlefa.putString("shelfLife", "");
                            bundlefa.putString("produntDate", "");
                            bundlefa.putString("goodsUnit", "");
                            bundlefa.putString("goodsPrice", "");
                            bundlefa.putString("releaseProv", "");
                            bundlefa.putString("releaseProvname", "");
                            bundlefa.putString("releaseCity", "");
                            bundlefa.putString("releaseCityname", "");
                            bundlefa.putString("currentAddress", "");
                            bundlefa.putString("exchangeClass", "");
                            bundlefa.putString("exchangeGoods", "");
                            bundlefa.putString("lat", "");
                            bundlefa.putString("lon", "");
                            ActivityUtils.startActivity(bundlefa,FaBuActivity.class);
                        }


                    }
                });
    }

    public void Updata(){
        RetrofitTask.getInstance()
                .createApi(Api.class)
                .getVersion("1")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new MyObserver(this,false) {
                    @Override
                    protected void onError(String errorMsg) {

                    }

                    @Override
                    protected void onSuccess(String JsonStr) {
                        Log.e("yier",JsonStr+"");
                        Gson gson=new Gson();
                        Updatagenxin updatagenxin=gson.fromJson(JsonStr,Updatagenxin.class);
                        if(updatagenxin.getData().getStatus().equals("1")){
                            if(Integer.valueOf(updatagenxin.getData().getVersion_no())>initLocalVersion()){
                                XUpdate.newBuild(MainActivity.this)
                                        .updateUrl(Contest.Baseeurl+"phone/jjyh/user/getVersion")
                                        .updateChecker(new DefaultUpdateChecker() {
                                            @Override
                                            public void onBeforeCheck() {
                                                super.onBeforeCheck();
                                                CProgressDialogUtils.showProgressDialog(MainActivity.this, "查询中...");
                                            }

                                            @Override
                                            public void onAfterCheck() {
                                                super.onAfterCheck();
                                                Log.e("zheli","走了这儿离");
                                                CProgressDialogUtils.cancelProgressDialog(MainActivity.this);
                                            }
                                        })
                                        .updateParser(new CustomUpdateParser())
                                        .updatePrompter(new CustomUpdatePrompter(MainActivity.this))
                                        .update();
                            }

                        }


                    }
                });
    }

    public int  initLocalVersion() {
        int mVersionCode=1;
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(this.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(this.getPackageName(), 0);
            mVersionCode = packageInfo.versionCode;
            //mVersionName = packageInfo.versionName;

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } finally {

        }
        return mVersionCode;
    }
}
